package com.lekang.le.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.lekang.common.annotation.Anonymous;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.lekang.common.annotation.Log;
import com.lekang.common.core.controller.BaseController;
import com.lekang.common.core.domain.AjaxResult;
import com.lekang.common.enums.BusinessType;
import com.lekang.le.domain.AppointmentRegistration;
import com.lekang.le.service.IAppointmentRegistrationService;
import com.lekang.common.utils.poi.ExcelUtil;
import com.lekang.common.core.page.TableDataInfo;

/**
 * 预约登记Controller
 * 
 * @author caoyangyang
 * @date 2025-10-14
 */
@RestController
@RequestMapping("/le/registration")
public class AppointmentRegistrationController extends BaseController
{
    @Autowired
    private IAppointmentRegistrationService appointmentRegistrationService;

    /**
     * 查询预约登记列表
     */
    @PreAuthorize("@ss.hasPermi('le:registration:list')")
    @GetMapping("/list")
    public TableDataInfo list(AppointmentRegistration appointmentRegistration)
    {
        startPage();
        List<AppointmentRegistration> list = appointmentRegistrationService.selectAppointmentRegistrationList(appointmentRegistration);
        return getDataTable(list);
    }

    /**
     * 导出预约登记列表
     */
    @PreAuthorize("@ss.hasPermi('le:registration:export')")
    @Log(title = "预约登记", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AppointmentRegistration appointmentRegistration)
    {
        List<AppointmentRegistration> list = appointmentRegistrationService.selectAppointmentRegistrationList(appointmentRegistration);
        ExcelUtil<AppointmentRegistration> util = new ExcelUtil<AppointmentRegistration>(AppointmentRegistration.class);
        util.exportExcel(response, list, "预约登记数据");
    }

    /**
     * 获取预约登记详细信息
     */
    @PreAuthorize("@ss.hasPermi('le:registration:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(appointmentRegistrationService.selectAppointmentRegistrationById(id));
    }

    /**
     * 新增预约登记
     */
    @PreAuthorize("@ss.hasPermi('le:registration:add')")
    @Log(title = "预约登记", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AppointmentRegistration appointmentRegistration)
    {
        return toAjax(appointmentRegistrationService.insertAppointmentRegistration(appointmentRegistration));
    }

    /**
     * 修改预约登记
     */
    @PreAuthorize("@ss.hasPermi('le:registration:edit')")
    @Log(title = "预约登记", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AppointmentRegistration appointmentRegistration)
    {
        return toAjax(appointmentRegistrationService.updateAppointmentRegistration(appointmentRegistration));
    }

    /**
     * 删除预约登记
     */
    @PreAuthorize("@ss.hasPermi('le:registration:remove')")
    @Log(title = "预约登记", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(appointmentRegistrationService.deleteAppointmentRegistrationByIds(ids));
    }


    //新增修改接口，修改到院时间
    @PreAuthorize("@ss.hasPermi('le:registration:edit')")
    @Log(title = "修改到院时间", businessType = BusinessType.UPDATE)
    @PutMapping("update")
    public AjaxResult update(@RequestBody AppointmentRegistration appointmentRegistration)
    {
        return toAjax(appointmentRegistrationService.updateAppointmentRegistrationArrivaltimeById(appointmentRegistration));
    }

    /**
     * 小程序预约登记（无需权限验证）
     * 限制：每个账号每天预约次数（探访+参观）不超过3次
     */
    @Anonymous
    @PostMapping("/miniApp")
    public AjaxResult miniAppAppointment(@RequestBody AppointmentRegistration appointmentRegistration)
    {
        // 检查今天的预约次数
        Long wxUserId = appointmentRegistration.getWxUserId();
        if (wxUserId == null) {
            return error("用户ID不能为空");
        }
        
        int todayCount = appointmentRegistrationService.getTodayAppointmentCount(wxUserId);
        if (todayCount >= 3) {
            return error("今天的预约次数已达上限（3次），请明天再试");
        }
        
        return toAjax(appointmentRegistrationService.insertAppointmentRegistration(appointmentRegistration));
    }

    /**
     * 查询我的预约列表（小程序端使用）
     * 
     * @param wxUserId 微信用户ID
     * @param status 预约状态（可选）
     * @return 预约列表
     */
    @Anonymous
    @GetMapping("/myAppointments")
    public AjaxResult getMyAppointments(
            @RequestParam(value = "wxUserId", required = true) Long wxUserId,
            @RequestParam(value = "status", required = false) String status)
    {
        AppointmentRegistration query = new AppointmentRegistration();
        query.setWxUserId(wxUserId);
        if (status != null && !status.isEmpty()) {
            query.setStatus(status);
        }
        List<AppointmentRegistration> list = appointmentRegistrationService.selectAppointmentRegistrationList(query);
        return success(list);
    }

    /**
     * 取消预约（小程序端使用）
     * 限制：每个账号每天取消预约次数不超过3次
     * 
     * @param appointmentId 预约ID
     * @param wxUserId 微信用户ID（用于安全验证）
     * @return 结果
     */
    @Anonymous
    @PostMapping("/cancelAppointment")
    public AjaxResult cancelAppointment(
            @RequestParam(value = "appointmentId", required = true) Long appointmentId,
            @RequestParam(value = "wxUserId", required = true) Long wxUserId)
    {
        // 检查今天的取消预约次数
        int todayCancelCount = appointmentRegistrationService.getTodayCancelCount(wxUserId);
        if (todayCancelCount >= 3) {
            return error("今天的取消预约次数已达上限（3次），请明天再试");
        }
        
        // 查询预约信息，验证权限
        AppointmentRegistration appointment = appointmentRegistrationService.selectAppointmentRegistrationById(appointmentId);
        
        if (appointment == null) {
            return error("预约不存在");
        }
        
        // 验证是否是当前用户的预约
        if (!appointment.getWxUserId().equals(wxUserId)) {
            return error("无权限取消该预约");
        }
        
        // 检查是否已经是取消状态
        if ("4".equals(appointment.getStatus())) {
            return error("该预约已取消，无需重复操作");
        }
        
        // 更新状态为已取消（4）
        AppointmentRegistration update = new AppointmentRegistration();
        update.setId(appointmentId);
        update.setStatus("4"); // 已取消
        
        int result = appointmentRegistrationService.updateAppointmentRegistration(update);
        if (result > 0) {
            return success("预约已取消");
        } else {
            return error("取消失败");
        }
    }

}
